﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FyndSharp.Data;
using System.Data.Common;
using System.Data;
using FyndSharp.Utilities.Common;
using FyndSharp.BusinessLogic;
using FyndSharp.Data.Orm;

namespace Fynd.Hermes.Web.Objects
{
    public class UserLogic : BaseLogic
    {
        private AdoSession _DbSession;

        public override void Initialize()
        {
            _DbSession = AdoSessionManager.Current["hermes"];
        }

        /// <summary>
        /// 修改用户的密码，将会先验证用户旧密码，只有在旧密码正确时才会将密码修改为新密码
        /// </summary>
        /// <param name="username">要修改用户密码的用户登录名</param>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>True修改成功，False修改失败</returns>
        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (oldPassword.Equals(newPassword))
            {
                return false;
            }

            bool isSessionOpen = false;
            try
            {
                isSessionOpen = _DbSession.Open();
                // 检查用户名和旧密码是否是有效的
                using (DbCommand checkCmd = _DbSession.CreateCommand())
                {
                    checkCmd.CommandText = "SELECT 1 FROM user WHERE login_name=@login_name AND password=@password";
                    checkCmd.Parameters.Add(_DbSession.CreateParameter("@login_name", DbType.String, username));
                    checkCmd.Parameters.Add(_DbSession.CreateParameter("@password", DbType.String, oldPassword));

                    if (false == TypeConvert.ToBool(_DbSession.ExecuteScalar(checkCmd)))
                    {
                        return false;
                    }
                }

                using (DbCommand updateCmd = _DbSession.CreateCommand())
                {
                    updateCmd.CommandText = "UPDATE user SET password=@password WHERE login_name=@login_name";
                    updateCmd.Parameters.Add(_DbSession.CreateParameter("@login_name", DbType.String, username));
                    updateCmd.Parameters.Add(_DbSession.CreateParameter("@password", DbType.String, newPassword));

                    return TypeConvert.ToBool(_DbSession.ExecuteNonQuery(updateCmd));
                }
            }
            finally
            {
                if (isSessionOpen)
                {
                    _DbSession.Close();
                }
            }
        }

        public bool SaveUser(UserInfomation anUser)
        {
            Checker.Assert<ArgumentNullException>(null != anUser);
            Checker.Assert<ArgumentException>(!String.IsNullOrEmpty(anUser.EmployeeNumber));
            Checker.Assert<ArgumentException>(!String.IsNullOrEmpty(anUser.LoginName));
            Checker.Assert<ArgumentException>(!String.IsNullOrEmpty(anUser.Password));
            Checker.Assert<ArgumentException>(!String.IsNullOrEmpty(anUser.TrueName));

            anUser.CreatedBy = Context.User.Name;
            anUser.CreatedDate = DateTime.Now;
            anUser.ModifiedBy = Context.User.Name;
            anUser.ModifiedDate = DateTime.Now;

            OrmObjectFactory theOrmObjectFactory = new OrmObjectFactory(
                new OrmObjectFactory.NextPrimaryValueHandler(
                    delegate()
                    {
                        return Guid.NewGuid().ToString();
                    }
                )
                , _DbSession
            );
            bool isSessionOpen = false;
            try
            {
                isSessionOpen = _DbSession.Open();

                DbCommand cmd = theOrmObjectFactory.CreateSaveDbCommand(anUser);

                return TypeConvert.ToBool(_DbSession.ExecuteNonQuery(cmd));
            }
            finally
            {
                if (isSessionOpen)
                {
                    _DbSession.Close();
                }
            }

        }

        public bool CheckLoginNameExists(string aLoginName)
        {
            Checker.Assert<System.ArgumentNullException>(!String.IsNullOrEmpty(aLoginName));

            string sql = "SELECT 1 FROM user WHERE login_name = @login_name";
            bool isSessionOpen = false;
            try
            {
                isSessionOpen = _DbSession.Open();

                using (DbCommand cmd = _DbSession.CreateCommand(sql))
                {
                    cmd.Parameters.Add(_DbSession.CreateParameter("@login_name", DbType.String, aLoginName));

                    return TypeConvert.ToBool(_DbSession.ExecuteScalar(cmd));
                }
            }
            finally
            {
                if (isSessionOpen)
                {
                    _DbSession.Close();
                }
            }
        }
        /// <summary>
        /// 通过登录名和密码获取用户信息
        /// </summary>
        /// <param name="aLoginName"></param>
        /// <param name="aPassword"></param>
        /// <returns>指定用户名和密码对应的用户信息，null表示没有找到对应的用户</returns>
        /// <exception cref="System.ArgumentNullException">当aLoginName或aPassword为null或等于String.Empty时抛出</exception>
        public UserInfomation FetchUserBy(string aLoginName, string aPassword)
        {
            Checker.Assert<System.ArgumentNullException>(!String.IsNullOrEmpty(aLoginName));
            Checker.Assert<System.ArgumentNullException>(!String.IsNullOrEmpty(aPassword));

            string sql = OrmObjectFactory.CreateSelectSql(typeof(UserInfomation));
            sql += " WHERE login_name=@login_name AND password=@password";

            bool isSessionOpen = false;
            try
            {
                isSessionOpen = _DbSession.Open();

                using (DbCommand cmd = _DbSession.CreateCommand(sql))
                {
                    cmd.Parameters.Add(_DbSession.CreateParameter("@login_name", DbType.String, aLoginName));
                    cmd.Parameters.Add(_DbSession.CreateParameter("@password", DbType.String, aPassword));

                    DataTable dt = _DbSession.ExecuteDataTable(cmd);
                    if (dt.Rows.Count > 0)
                    {
                        UserInfomation theUser = OrmObjectFactory.CreateOrmObject<UserInfomation>(dt.Rows[0]);
                        return theUser;
                    }
                    return null;
                }
            }
            finally
            {
                if (isSessionOpen)
                {
                    _DbSession.Close();
                }
            }
        }

        public UserInfomation FetchUserBy(string anUserId)
        {
            Checker.Assert<System.ArgumentNullException>(!String.IsNullOrEmpty(anUserId));

            string sql = OrmObjectFactory.CreateSelectSql(typeof(UserInfomation));
            sql += " WHERE user_id=@user_id";

            bool isSessionOpen = false;
            try
            {
                isSessionOpen = _DbSession.Open();

                using (DbCommand cmd = _DbSession.CreateCommand(sql))
                {
                    cmd.Parameters.Add(_DbSession.CreateParameter("@user_id", DbType.String, anUserId));

                    DataTable dt = _DbSession.ExecuteDataTable(cmd);
                    if (dt.Rows.Count > 0)
                    {
                        UserInfomation theUser = OrmObjectFactory.CreateOrmObject<UserInfomation>(dt.Rows[0]);
                        return theUser;
                    }
                    return null;
                }
            }
            finally
            {
                if (isSessionOpen)
                {
                    _DbSession.Close();
                }
            }
        }

    }
}